package com.lw.leetcode.node;

/**
 * 剑指 Offer 55 - II. 平衡二叉树
 * 面试题 04.04. 检查平衡性
 *
 * @Author liw
 * @Date 2021/5/13 13:00
 * @Version 1.0
 */
public class IsBalanced {

    public boolean isBalanced(TreeNode root) {
        return find(root) >= 0;
    }

    private int find(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int l = find(node.left);
        if (l < 0) {
            return l;
        }
        int r = find(node.right);
        if (r < 0) {
            return r;
        }
        if (Math.abs(l - r) > 1) {
            return -1;
        }
        return Math.max(l, r) + 1;
    }


}
